package com.wxtt.android.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fast.dev.frame.glide.BitmapUtils;
import com.fast.dev.frame.glide.GlideLoader;
import com.fast.dev.frame.listener.ProgressWebViewListener;
import com.fast.dev.frame.ui.Bind;
import com.fast.dev.frame.ui.V;
import com.fast.dev.frame.utils.ToolUtils;
import com.fast.dev.frame.utils.WebViewUtils;
import com.fast.dev.frame.view.ProgressWebView;
import com.three.WxUtils;
import com.wxtt.android.R;
import com.wxtt.android.animation.AnimatorUtils;
import com.wxtt.android.bean.WxArticleBean;
import com.wxtt.android.common.CommonActivity;
import com.wxtt.android.config.SpConfig;
import com.wxtt.android.dialog.ShareDialog;
import com.wxtt.android.realm.FavouriteRealmUtils;
import com.wxtt.android.widget.EmptyBridge;

/**
 * 说明：文章详情
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/1/19 16:05
 * <p/>
 * 版本：verson 1.0
 */
public class AriticleDetailActivity extends CommonActivity implements ShareDialog.ShareListener {

    @Bind(id = R.id.webview)
    private ProgressWebView webview;
    @Bind(id = R.id.progressbar)
    private ProgressBar progressbar;
    @Bind(id = R.id.empty_bridge)
    private EmptyBridge empty_bridge;
    @Bind(id = R.id.rl_loved_container,click = true)
    private RelativeLayout rl_loved_container;
    @Bind(id = R.id.tv_come)
    private TextView tv_come;

    private View iv_loved_yes,iv_loved_no;

    private FavouriteRealmUtils mFavouriteDB;
    private WxArticleBean articleBean;
    private ShareDialog mShareDialog;
    private Toolbar toolbar;
    //标记该文章是否收藏
    private boolean isLoved;

    @Override
    public int setRootView() {
        return R.layout.activity_ariticle_detail;
    }

    @Override
    public void onInit(Bundle bundle) {
        articleBean = getIntent().getBundleExtra("detailBundle").getParcelable("detailBundle");
        if (articleBean == null){
            return;
        }
        mFavouriteDB = new FavouriteRealmUtils(this);
        //设置来源
        V.setText(tv_come,R.string.str_detail_come,articleBean.getSource());
        toolbar.setTitle(articleBean.getTitle());
        WebViewUtils.webViewInit(webview, this, articleBean.getUrl());

        webview.setProgressListener(new ProgressWebViewListener() {
            @Override
            public void onProgress(WebView webView, int progress) {
                progressbar.setProgress(progress);
                if (progress == 100) {
                    progressbar.setVisibility(View.GONE);
                } else {
                    if (progressbar.getVisibility() == View.GONE) {
                        progressbar.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (errorCode == -7 || errorCode == -13 || errorCode == -14){
                    shortToast(description);
                }else {
                    loadingError();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                addImageClickListener();
            }
        });

        //播放视频
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setLoadWithOverviewMode(true);

        //处理图片点击
        handlerPic(settings);
        //初始化收藏状态
        initLovedState();
    }

    /**
     * 说明：初始化收藏状态
     */
    private void initLovedState() {
        iv_loved_no = bind(R.id.item_image_loved_no);
        iv_loved_yes = bind(R.id.item_image_loved_yes);
        isLoved = mFavouriteDB.isFavourite(articleBean);
        AnimatorUtils.animateHeart(iv_loved_yes, iv_loved_no, isLoved);
    }

    @Override
    protected int setMenu() {
        return R.menu.detail_menu;
    }

    @Override
    protected void onMenuItemClick(int id) {
        super.onMenuItemClick(id);
        switch (id){
            case R.id.detail_meun_share:
                if (mShareDialog == null){
                    mShareDialog = new ShareDialog(this,this);
                }
                mShareDialog.show();
                break;
            case R.id.detail_meun_refresh:
                reload();
                break;
            case R.id.detail_meun_open_browser:
                if (articleBean != null){
                    ToolUtils.openBrowser(this, articleBean.getUrl());
                }
                break;
        }
    }

    /**
     * 说明：注入js代码
     */
    private void addImageClickListener(){
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        webview.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++){" +
                "objs[i].onclick=function(){" +
                "window.imagelistner.openImage(this.src);}})()");
    }

    /**
     * 说明：处理点击的图片
     * @param settings
     */
    private void handlerPic(WebSettings settings){
        webview.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
    }

    /**
     * 说明：加载失败
     */
    private void loadingError(){
        V.VISIBLE(empty_bridge);
        empty_bridge.setMyView(webview);
        empty_bridge.setFailState(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reload();
            }
        });
    }

    /**
     * 说明：重新加载网页
     */
    private void reload(){
        empty_bridge.setSuccessState();
        webview.reload();
    }

    @Override
    protected boolean showToolbar() {
        return true;
    }
    @Override
    protected void onCustomToolbar(View view, Toolbar toolbar) {
        this.toolbar = toolbar;
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            webview.getClass().getMethod("onPause").invoke(webview, (Object[]) null);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            webview.getClass().getMethod("onResume").invoke(webview, (Object[]) null);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public int setToolbarTitle() {
        return R.string.ariticle_detail;
    }

    /**
     * 说明：分享朋友
     */
    @Override
    public void shareWechat() {
        if (articleBean != null){
            GlideLoader.bitmap(this, articleBean.getFirstImg(), new GlideLoader.BitmapListener() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    WxUtils.sharePage(AriticleDetailActivity.this,articleBean.getUrl(),articleBean.getTitle(),articleBean.getTitle(), bitmap,WxUtils.SCENE_SESSION);
                }

                @Override
                public void onStart() {

                }

                @Override
                public void onFail(Exception e) {
                    WxUtils.sharePage(AriticleDetailActivity.this,articleBean.getUrl(),articleBean.getTitle(),articleBean.getTitle(), BitmapUtils.bitmap(AriticleDetailActivity.this,R.mipmap.app),WxUtils.SCENE_SESSION);
                }
            });
        }
        mShareDialog.dismiss();
    }

    /**
     * 说明：分享朋友圈
     */
    @Override
    public void shareWxcircle() {
        if (articleBean != null){
            GlideLoader.bitmap(this, articleBean.getFirstImg(), new GlideLoader.BitmapListener() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    WxUtils.sharePage(AriticleDetailActivity.this,articleBean.getUrl(),articleBean.getTitle(),articleBean.getTitle(), bitmap,WxUtils.SCENE_TIMELINE);
                }

                @Override
                public void onStart() {

                }

                @Override
                public void onFail(Exception e) {
                    WxUtils.sharePage(AriticleDetailActivity.this,articleBean.getUrl(),articleBean.getTitle(),articleBean.getTitle(), BitmapUtils.bitmap(AriticleDetailActivity.this,R.mipmap.app),WxUtils.SCENE_TIMELINE);
                }
            });
        }
        mShareDialog.dismiss();
    }

    /**
     * 说明：JS处理图片
     */
    public class JavascriptInterface{
        private Context mContext;
        public JavascriptInterface(Context context){
            mContext = context;
        }
        public void openImage(String img){
            Bundle bundle = new Bundle();
            bundle.putString("url",img);
            showActivity(AriticleDetailActivity.this, ShowImageActivity.class, bundle);
        }
    }

    @Override
    public void clickView(View v) {
        switch (v.getId()){
            case R.id.rl_loved_container:
                if (SpConfig.isLogin()){
                    isLoved = !isLoved;
                    setLoved(isLoved);
                    if (isLoved){
                        shortToast("添加收藏");
                    }else {
                        shortToast("取消收藏");
                    }
                }else {
                    showActivity(this,LoginActivity.class);
                }
                break;
        }
    }

    /**
     * 说明：设置是否收藏
     */
    private void setLoved(boolean isLoved) {
        AnimatorUtils.animateHeart(iv_loved_yes, iv_loved_no, isLoved);
        mFavouriteDB.favourite(isLoved, articleBean);
    }
}
